package com.xiangzi.nba;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.xiangzi.bean.nba.Match;
import com.xiangzi.bean.nba.MatchScore;
import com.xiangzi.bean.nba.Player;
import com.xiangzi.bean.nba.Team;
import com.xiangzi.http.HTTPRequest;
import com.xiangzi.http.HttpTool;
import com.xiangzi.util.DateUtils;
import com.xiangzi.util.JSONUtil;

public class NetEaseNBA {

	private static Logger logger = LoggerFactory.getLogger(NetEaseNBA.class);

	/**
	 * 每日比赛场次和结果 <br/>
	 * <p>
	 * 网页：http://nba.sports.163.com/20161026.html <br/>
	 * 数据获取地址:http://nba.sports.163.com/2016/match/daily/20161026.html <br/>
	 * </p>
	 * 
	 * @param day
	 *            格式：yyyyMMdd
	 * @return
	 */
	public List<Match> matchDaily(String day) {
		String url = "http://nba.sports.163.com/" + day.substring(0, 4) + "/match/daily/" + day + ".html";

		Map<String, Object> paramMap = new HashMap<String, Object>(20);
		String content = getData(url, paramMap);
		logger.error(">>>>>>>>>>" + content);

		List<Match> matchList = null;
		if (StringUtils.isNotBlank(content)) {
			matchList = JSONUtil.parseObject(content, new TypeReference<List<Match>>() {
			});
		}

		return matchList;
	}

	/**
	 * 比赛记分板 <br/>
	 * <p>
	 * 网页：http://nba.sports.163.com/2016/match/stat/1673994.html <br/>
	 * 比分数据:http://nba.sports.163.com/2016/match/scoreboard/1673994.html <br/>
	 * </p>
	 * 
	 * @param sid
	 * @param mid
	 */
	public void matchScoreboard(String sid, String mid) {
		String url = "http://nba.sports.163.com/" + sid + "/match/scoreboard/" + mid + ".html";
		Map<String, Object> paramMap = new HashMap<String, Object>(20);
		String content = getData(url, paramMap);
		logger.error(">>>>>>>>>>" + content);
	}

	/**
	 * 比赛球队数据和个人数据 <br/>
	 * <p>
	 * 网页：http://nba.sports.163.com/2016/match/stat/1673994.html <br/>
	 * 球员数据:http://nba.sports.163.com/2016/match/boxscore/1673994.html <br/>
	 * </p>
	 * 
	 * @param sid
	 * @param mid
	 */
	public MatchScore matchBoxscore(String sid, String mid) {
		String url = "http://nba.sports.163.com/" + sid + "/match/boxscore/" + mid + ".html";
		Map<String, Object> paramMap = new HashMap<String, Object>(20);
		String content = getData(url, paramMap);
		logger.error(">>>>>>>>>>" + content);
		MatchScore matchScore = null;
		if (StringUtils.isNotBlank(content)) {
			matchScore = JSONUtil.parseObject(content, MatchScore.class);
		}
		return matchScore;
	}

	/**
	 * 球队队员 <br/>
	 * <p>
	 * 1:http://nba.sports.163.com/team/10/ <br/>
	 * 2:http://nba.sports.163.com/team/10/structure/ <br/>
	 * </p>
	 * 
	 * @param teamId
	 *            球队ID
	 * @return
	 */
	public List<Player> teamPlayers(String teamId) {
		String url = "http://nba.sports.163.com/team/" + teamId;
		url = "http://nba.sports.163.com/team/" + teamId + "/structure";
		List<Player> playerList = new ArrayList<>();
		try {
			Document doc = Jsoup.connect(url).get();
			Elements items = doc.select("table[class=\"dataTB2 dataTB3\"]");
			Elements trs = items.get(0).select("tr");
			for (int i = 1; i < trs.size(); i++) {
				Elements tds = trs.get(i).select("td");
				Player player = new Player();
				player.setClothesNum(tds.get(0).text());
				player.setName(tds.get(1).text());
				// <a href="/player/908263/">周琦</a>
				player.setId(Jsoup.parse(tds.get(1).html()).select("a").get(0).attr("href").replace("/player/", "").replace("/", ""));
				player.setPosition(tds.get(2).text());
				player.setHeight(Double.parseDouble(tds.get(3).text()));
				player.setWeight(Double.parseDouble(tds.get(4).text()));
				player.setAge(Integer.parseInt(tds.get(5).text()));
				player.setCareer(Integer.parseInt(tds.get(6).text()));
				player.setUniversity(tds.get(7).text());
				player.setYearSalary(tds.get(8).text());

				playerList.add(player);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return playerList;
	}

	/**
	 * 所有球队信息
	 */
	public List<Team> teams() {
		List<Team> list = new ArrayList<>();

		String url = "http://nba.sports.163.com/team";
		try {
			Document doc = Jsoup.connect(url).get();
			Elements items = doc.select("div[class=\"listItem\"]");
			for (int i = 0; i < items.size(); i++) {
				Document teamDoc = Jsoup.parse(items.get(i).html());
				Elements eles = teamDoc.select("a");
				Team team = new Team();
				team.setId(eles.get(0).attr("href").replace("/team/", "").replace("/", ""));
				team.setName(eles.get(1).text());
				// team.setLogo(teamDoc.select("img").get(0).attr("src"));
				StringBuffer logoBuff = new StringBuffer();
				logoBuff.append("http://nba.sports.163.com/2016/images/team/hbg/team" + team.getId() + ".gif").append(",");
				logoBuff.append("http://nba.sports.163.com/2016/images/team/90/team" + team.getId() + ".gif").append(",");
				logoBuff.append("http://nba.sports.163.com/2016/images/team/banner/team" + team.getId() + ".gif").append(",");
				team.setLogo(logoBuff.toString());

				list.add(team);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return list;
	}

	/**
	 * 球队详细信息
	 * 
	 * @param team
	 */
	public void teamDetail(Team team) {
		String url = "http://nba.sports.163.com/team/" + team.getId();
		try {
			Document doc = Jsoup.connect(url).get();
			// Elements eles = doc.select("h1[class=\"h1btitle\"]");
			// logger.error(eles.html());
			team.setNameEn(doc.select("span[class=\"f18b-b\"]").text());
			team.setArea(StringUtils.split(doc.select("span[class=\"f14px\"]").text(), " ")[1].substring(0, 2));

			String info = doc.select("span[class=\"nor-dblue\"]").text();
			String[] infoArray = StringUtils.split(info, "：");
			team.setAreaSub(infoArray[infoArray.length - 1].replace("区赛区", ""));
			
			logger.error(JSONUtil.toJSONString(team));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 球员详细信息
	 */
	public void playerDetail(Player player) {
		String url = "http://nba.sports.163.com/player/" + player.getId();
		try {
			Document doc = Jsoup.connect(url).get();
			Elements eles = doc.select("span[class=\"nor-dblue\"]");
			player.setNameEn(StringUtils.split(eles.get(0).text(), "|")[1]);
			String[] infoArray = StringUtils.split(eles.get(1).text(), "：");
			player.setBirthday(DateUtils.format(DateUtils.parseDate(StringUtils.replace(infoArray[3], "生于", "").trim(), "yyyy-M-d"), "yyyy-MM-dd"));
			player.setBirthplace(StringUtils.replace(infoArray[4], "毕业大学", "").trim());
			player.setDraft(infoArray[infoArray.length-1]);
			player.setAvatar("http://nba.sports.163.com/2016/images/player/small/"+player.getId()+".jpg");
			
			logger.error(JSONUtil.toJSONString(player));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private String getData(String url, Map<String, Object> paramMap) {
		HTTPRequest request = HttpTool.url(url).form(paramMap);
		HttpResponse response = request.get();
		String content = null;
		if (200 == HttpTool.getStatus(response) && HttpTool.isStatusOK(response)) {
			content = HttpTool.getResponseAsString(response);
		}
		return content;
	}

	public static void main(String[] args) throws IOException {
		NetEaseNBA netEaseNBA = new NetEaseNBA();

		// String day = "20161027";
		//
		// List<Match> matchList = netEaseNBA.matchDaily(day);
		// logger.error(">>>>>>>>>>matchList.size:" + matchList.size());
		//
		// for (Match match : matchList) {
		// // netEaseNBA.matchScoreboard(match.getSid(), match.getMid());
		//
		// MatchScore matchScore = netEaseNBA.matchBoxscore(match.getSid(),
		// match.getMid());
		//
		// logger.error(">>>>>>>>>>AwayPoint:" +
		// matchScore.getAwayTotal().getPoint());
		// logger.error(">>>>>>>>>>HomePoint:" +
		// matchScore.getHomeTotal().getPoint());
		//
		// }

		// List<Team> teamList = netEaseNBA.teams();
		//
		// for (Team team : teamList) {
		// // netEaseNBA.teamPlayers(team.getId());
		// logger.error(team.getName());
		// netEaseNBA.teamDetail(team);
		// }

		List<Player> teamPlayers = netEaseNBA.teamPlayers("10");// 公牛
		for (Player player : teamPlayers) {
			netEaseNBA.playerDetail(player);
		}

	}

}
